package db

import (
	"fmt"
	"time"
	
)




// TableName 指定表名


// UserSignup 用户注册
func UserSignup(username, passwd, email, s3key, secret string) bool {
	user := User{
		UserName:   username,
		UserPwd:    passwd,
		Email:      email,
		AccessKey:  s3key,
		SecretKey:  secret,
		SignupAt:   time.Now(),
		LastActive: time.Now(),
	}

	result := DB.Create(&user)
	if result.Error != nil {
		fmt.Printf("Failed to create user: %v\n", result.Error)
		return false
	}
	return true
}

// UserSignin 用户登录
func UserSignin(username, encpwd string) bool {
	var user User
	err := DB.Where("user_name = ? AND user_pwd = ? AND status = 0", 
		username, encpwd).First(&user).Error
	return err == nil
}

// UpdateToken 更新用户token
func UpdateToken(username, token string) bool {
	// 使用 upsert 操作
	userToken := UserToken{
		UserName:  username,
		Token:     token,
		ExpiredAt: time.Now().Add(24 * time.Hour), // token 24小时后过期
	}

	result := DB.Where("user_name = ?", username).
		Assign(UserToken{Token: token, ExpiredAt: time.Now().Add(24 * time.Hour)}).
		FirstOrCreate(&userToken)

	return result.Error == nil
}

// GetUsername 通过token获取用户名
func GetUsername(token string) (string, error) {
	var userToken UserToken
	err := DB.Where("user_token = ? AND expired_at > ?", 
		token, time.Now()).First(&userToken).Error
	if err != nil {
		return "", err
	}
	return userToken.UserName, nil
}

// GetUserInfo 获取用户信息
func GetUserInfo(username string) (User, error) {
	var user User
	err := DB.Select("user_name, signup_at, AccessKey, SecretKey").
		Where("user_name = ? AND status = 0", username).
		First(&user).Error
	return user, err
}
